package me.keiwu.admin.service.impl;

import me.keiwu.admin.domain.PosterTemplate;
import me.keiwu.admin.dao.PosterTemplateRepository;
import me.keiwu.admin.service.PosterService;
import me.keiwu.admin.util.EntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by kei on 02/11/2017.
 */
@Service
@Transactional
public class PosterServiceImpl implements PosterService {

    @Autowired
    private PosterTemplateRepository posterTemplateRepository;

    @Override
    public Long addTemplate(String title, String desc, String imgSrc, String editData) {
        PosterTemplate template = new PosterTemplate();
        template.setTitle(title);
        template.setDescription(desc);
        template.setImgSrc(imgSrc);
        template.setEditData(editData);
        EntityUtil.setModifiedBy(template, true);
        PosterTemplate t = posterTemplateRepository.save(template);
        if (t == null) return null;
        return t.getId();
    }

    @Override
    public boolean updateTemplate(Long id, String title, String desc, String imgSrc, String editData) {
        PosterTemplate template = posterTemplateRepository.findOne(id);
        if (template == null) return false;
        template.setTitle(title);
        template.setDescription(desc);
        template.setImgSrc(imgSrc);
        template.setEditData(editData);
        EntityUtil.setModifiedBy(template);
        posterTemplateRepository.save(template);
        return true;
    }


    @Override
    public Page<PosterTemplate> findByPageAndSize(int page, int size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        return posterTemplateRepository.findAll(pageable);
    }


    @Override
    public PosterTemplate findById(Long id) {
        return posterTemplateRepository.findOne(id);
    }
}
